package com.itheima.configuration;

import com.itheima.jobs.ClearImgJob;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {
    @Bean(name = "jobDetail")
    public MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean(ClearImgJob clearImgJob){
        MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
        methodInvokingJobDetailFactoryBean.setName("jobDetail");

        //需要执行的对象
        methodInvokingJobDetailFactoryBean.setTargetObject(clearImgJob);

        //需要执行的方法
        methodInvokingJobDetailFactoryBean.setTargetMethod("clearImg");

        return methodInvokingJobDetailFactoryBean;
    }

    @Bean(name = "jobTigger")
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetail jobDetail) {
        CronTriggerFactoryBean tigger = new CronTriggerFactoryBean();
        tigger.setJobDetail(jobDetail);

        //cron表达式，每天执行一次
//        tigger.setCronExpression("0 0 0 1/1 1/1 ? *");
        //cron表达式，每10秒执行一次
        tigger.setCronExpression("0/10 * * * * ?");
        tigger.setName("jobTigger");
        return tigger;
    }

    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactoryBean(Trigger jobTigger){
        SchedulerFactoryBean scheduler = new SchedulerFactoryBean();

        //注册触发器
        scheduler.setTriggers(jobTigger);

        return scheduler;
    }

}
